<?php

namespace App\Console\Commands\Guanyuan;

use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Service\Wanggui\WangguiDotService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class CacheCityPoint extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wanggui:cacheCityPoint';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '缓存城市的点位信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {

        // 判断数据是否已经缓存
        $shopCount = GuanyuanSyncShopListModel::query()->count();
        if (!$shopCount) {
            Artisan::call('guanyuan:shopList');
        }

        //获得所有的市
        $china = WangGuiCityByPower::getChinaDistrict();
        $cityArr = [];
        foreach ($china as $province) {
            foreach ($province['districts'] as $city) {
                $cityArr[] = str_replace('城区', '市', $city['name']);
            }
        }

        $countCity = count($cityArr);

        if (!$countCity) {
            return;
        }

        //缓存
        foreach ($cityArr as $key => $citySelf) {

            $this->info('已完成:' . round($key / $countCity, 4) * 100 . '%');

            // 删除缓存信息
            Redis::del('wanggui:cityPointLocation:' . $citySelf);
            Cache::forget('wanggui:cityPointInfo:' . $citySelf);

            $cityPointInfo = Cache::remember('wanggui:cityPointInfo:' . $citySelf, 86400, function () use ($citySelf){
                return WangguiDotService::cityPintByPc($citySelf);
            });

            // 将经纬度存入redis 方便距离查询
            foreach ($cityPointInfo as $cityPointType => $cityPoint) {
                foreach ($cityPoint as $point) {
                    Redis::geoAdd('wanggui:cityPointLocation:' . $citySelf, $point['lng'], $point['lat'], $cityPointType . '-' . $point['id']);
                }
            }
        }


        // 同步全国的网规信息
        // 清除缓存

        $this->info('同步全国的网规信息 ing ');
        Cache::forget('tiger:wanggui:pointStatistics');

        WangguiDotService::pointStatistics();
    }
}
